package cn.jn.lhm.part01;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import static cn.jn.lhm.part01.ByteBufferUtil.debugAll;

/**
 * @author lhm 2753914576@qq.com
 * @time 2022/7/3 - 15:42
 **/
public class ScatteringRead {
    public static void main(String[] args) {
        // 文件分散读取
        try (FileChannel channel = new RandomAccessFile(ScatteringRead.class.getResource("/").getFile() + "data.txt", "r").getChannel();
             FileChannel outputChannel = new RandomAccessFile(ScatteringRead.class.getResource("/").getFile() + "copy.txt", "rw").getChannel();) {

            // 可以实现文件的拷贝
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (channel.read(buffer) != 0) {
                buffer.flip();
                outputChannel.write(buffer);
                buffer.rewind();
            }

          /*  ByteBuffer buffer1 = ByteBuffer.allocate(3);
            ByteBuffer buffer2 = ByteBuffer.allocate(3);
            ByteBuffer buffer3 = ByteBuffer.allocate(5);
            channel.read(new ByteBuffer[]{buffer1, buffer2, buffer3});
//            buffer1.flip();
            debugAll(buffer1);
            debugAll(buffer2);
            debugAll(buffer3);*/
        } catch (Exception e) {
            // mute
            e.printStackTrace();
        }
    }
}
